package com.auditlog.format.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.auditlog.datasource.db.SqlType;
import com.auditlog.datasource.struct.FieldChangeLog;
import com.auditlog.datasource.struct.RecordImage;
import com.auditlog.datasource.struct.RowChangeLog;
import com.auditlog.datasource.struct.TableRecord;
import com.auditlog.format.AbstractRecordImageFormat;

import java.security.Key;
import java.util.*;

public class UpdateRecordImageFormat extends AbstractRecordImageFormat {

    @Override
    public void doFormat(RecordImage recordImage) {
        TableRecord beforeRecord = recordImage.getBeforeRecord();
        TableRecord afterRecord = recordImage.getAfterRecord();
        Map<String, List<Object>> before = beforeRecord.getRows();
        Map<String, List<Object>> after = afterRecord.getRows();
        String delimiter = afterRecord.getDelimiter();
        Set<String> removeKey = new HashSet<>();
        if (CollectionUtil.isNotEmpty(after)) {
            // 更新同一批中insert的数据（操作前查询不到数据的）
            after.forEach((k, v) -> {
                if (before == null || !before.containsKey(k)) {
                    removeKey.add(k);
                }
            });
        }
        if (CollectionUtil.isNotEmpty(before)) {
            // 更新的数据被同一批中的sql删除
            before.forEach((k, v) -> {
                if (after == null || !after.containsKey(k)) {
                    removeKey.add(k);
                }
            });
        }
        List<List<Object>> possibleUpdateOrDeletePks = recordImage.getPossibleUpdateOrDeletePks();
        this.removeKey(possibleUpdateOrDeletePks, removeKey, recordImage.getPkColumnsName(), delimiter);
    }

    @Override
    public Map<SqlType, List<RowChangeLog>> changeLog(RecordImage recordImage) throws Exception {
        return this.buildUpdateChangeLog(recordImage);
    }

    @Override
    public SqlType getType() {
        return SqlType.UPDATE;
    }

}
